from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QGraphicsView, QGraphicsScene
from PySide6.QtMultimedia import QMediaPlayer,QAudioOutput
from PySide6.QtCore import Qt, QUrl, QTimer

import sys
from queue import *
class AudioPlayerWidget(QWidget):
    def __init__(self, parent=None):
        super(AudioPlayerWidget, self).__init__(parent)
        self.mediaPlayer = QMediaPlayer(self)
        self.audioQueue=Queue()
        self.audioOutput = QAudioOutput() 
        self.mediaPlayer.setAudioOutput(self.audioOutput)
        self.audioOutput.setVolume(300)  # 设置音量
        self.layout = QVBoxLayout(self)
        # 播放按钮
        self.playButton = QPushButton("Play")
        self.playButton.clicked.connect(self.play)
        self.layout.addWidget(self.playButton)
        # 停止按钮
        self.stopButton = QPushButton("Stop")
        self.stopButton.clicked.connect(self.stop)
        self.layout.addWidget(self.stopButton)
        # 音频波形显示
        # self.waveformView = QGraphicsView()
        # self.waveformScene = QGraphicsScene()
        # self.waveformView.setScene(self.waveformScene)
        # self.layout.addWidget(self.waveformView)
        # # 设置波形显示的大小
        # self.waveformView.setFixedSize(400, 100)
        self.mediaPlayer.playbackStateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
       

    async def play(self):
        if self.mediaPlayer.source().isEmpty():
            self.loadNextAudio()
        else:
            self.mediaPlayer.play()
    def stop(self):
        self.mediaPlayer.stop()
    def mediaStateChanged(self, state):
        if self.mediaPlayer.playbackState == QMediaPlayer.PlaybackState.PlayingState:
            self.playButton.setText("Pause")
        else:
            self.playButton.setText("Play")
            self.loadNextAudio()
            
    def positionChanged(self, position):
        # 可以在这里更新音频波形显示
        pass
    def durationChanged(self, duration):
        # 可以在这里更新音频波形显示
        pass

    def loadAudio(self, filePath):
        self.audioQueue.put(filePath)
        if self.mediaPlayer.playbackState() != QMediaPlayer.PlaybackState.PlayingState:
            self.loadNextAudio()

    def checkPlaybackFinished(self):
        if self.mediaPlayer.position() >= self.mediaPlayer.duration():
            self.loadNextAudio()

    def loadNextAudio(self):
        if self.audioQueue.empty()==False:
            filePath = self.audioQueue.get()
            self.mediaPlayer.setSource(QUrl.fromLocalFile(filePath))
            self.mediaPlayer.play()
           
